package com.wcs.exam.common.handler;

import com.wcs.exam.common.base.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.StringJoiner;

/**
 * @author wcs
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.wcs.exam.controller.api"})
public class ApiHandlerException {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String processException(MethodArgumentNotValidException ex) {
        StringJoiner joiner = new StringJoiner("、");
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
            joiner.add(fieldError.getDefaultMessage());
        }
        log.error("MethodArgumentNotValidException, {}", joiner);
        return joiner.toString();
    }

    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String processException(Exception e) {
        log.error("Exception", e);
        return e.getMessage();
    }

    @ExceptionHandler({BaseException.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String processException(BaseException e) {
        log.error("BaseException", e);
        return e.getMessage();
    }

}
